<!-- @format -->

<template>
  <view class="repositories">
    <wd-navbar fixed placeholder safeAreaInsetTop>
      <template #capsule>
        <wd-navbar-capsule @back="handleBack" @back-home="handleBackHome" />
      </template>
      <template #title>
        <text class="title">我的</text>
      </template>
    </wd-navbar>

    <div class="more-tools">
      <the-icon-btn
        @click="toMinishare"
        icon="share"
        bgColor="#1bb56a"
        title="爱分享"
      />
      <the-icon-btn
        @click="toRedFlower"
        icon="chrome"
        bgColor="red"
        title="小红花"
      />
      <the-icon-btn
        @click="toBigAunt"
        icon="heart"
        bgColor="pink"
        title="经期预测"
      />
    </div>

    <view class="repositories-content">
      <view class="sub-cell">
        <text class="sub-title">我的列表</text>
        <view class="sub-cell-ope">
          <view v-if="isAdmin" class="btn-add" @click="toggleEnv">
            <wd-icon :name="envIconName"></wd-icon>
            {{ envTxt }}
          </view>
          <view class="btn-add" @click="scanRepository">
            <wd-icon name="scan"></wd-icon>
            扫瞄
          </view>
          <view class="btn-add" @click="showAddPopup">
            <wd-icon name="add"></wd-icon>
            添加
          </view>
        </view>
      </view>
      <div v-if="repositories.length" class="repositories-list">
        <base-book
          v-for="item in repositories"
          :key="item.ower + '-' + item.repo"
          :book="item"
          @click="openRepository($event)"
        >
          <wd-button
            custom-style="margin-right: 20rpx; color: #333;"
            type="text"
            @click.stop="refreshRepInfo(item)"
          >
            更新
          </wd-button>
          <wd-icon
            color="red"
            name="delete"
            @click.stop="removeRepository(item)"
        /></base-book>
      </div>
      <div v-else class="no-repositories">
        <wd-status-tip image="content" tip="暂无内容，添加一个" />
      </div>
    </view>

    <view v-if="hotBooks.length && !isPublish" class="repositories-content">
      <view class="sub-cell">
        <text class="sub-title">精选内容</text>
      </view>
      <div class="repositories-list">
        <base-book
          v-for="item in hotBooks"
          :key="item.ower + '-' + item.repo"
          :book="item"
          @click="openRepository($event)"
        ></base-book>
      </div>
    </view>

    <wd-toast></wd-toast>
    <wd-popup v-model="visible" position="top">
      <view class="popup-content">
        <input
          class="popup-input"
          v-model="newRepoUrl"
          placeholder="请输入 Gitee 项目地址"
        />
        <view class="popup-opes">
          <wd-button
            custom-class="popup-btn-add"
            :round="false"
            @click="addRepository"
          >
            添加
          </wd-button>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { useToast } from 'wot-design-uni'
import BaseBook from '../../components/BaseBook.vue'
import { useEnv } from '../../composables/useEnv'
import { useHotBook } from '../../composables/useHotBook'
import { useNavHome } from '../../composables/useNavHome'
import { useUserService } from '../../composables/useUserService'
import { GiteeService } from '../../services/GiteeService'
const visible = ref(false)
const toast = useToast()
const newRepoUrl = ref('')
const giteeService = new GiteeService()
const { toggleEnv, isPublish } = useEnv()

const { updateUserInfo, repositories, addRes, isAdmin } = useUserService()

const { hotBooks } = useHotBook({ mounted: true })

const { handleBack, handleBackHome } = useNavHome()

const isSameRepo = (item1, item2) => {
  return item1.owner === item2.owner && item1.repo === item2.repo
}

const envIconName = computed(() => (isPublish.value ? 'view' : 'eye-close'))
const envTxt = computed(() => (isPublish.value ? '切换生产' : '切换发布'))
const showAddPopup = () => {
  visible.value = true
}

// 去爱分享
const toMinishare = () => {
  uni.navigateTo({
    url: '/pages/minishare/minishare',
  })
}

// 去小红花
const toRedFlower = () => {
  uni.navigateTo({
    url: '/pages/red-flower/red-flower',
  })
}

// 去预测大姨妈
const toBigAunt = () => {
  uni.navigateTo({
    url: '/pages/big-aunt/big-aunt',
  })
}

const addRepository = () => {
  // https://gitee.com/tunie/nestjs-starter
  if (newRepoUrl.value) {
    const regex = /^https?:\/\/gitee\.com\/[a-zA-Z0-9-]+(\/[a-zA-Z0-9-]+)+$/
    if (!regex.test(newRepoUrl.value)) {
      toast.show('请输入正确的 Gitee 项目 URL')
      return
    }

    let [owner, repo] = newRepoUrl.value
      .replace('https://gitee.com/', '')
      .split('/')

    addRes({ owner, repo, toast })
    newRepoUrl.value = ''
    visible.value = false
  } else {
    toast.show('请输入内容')
  }
}

const scanRepository = () => {
  uni.scanCode({
    success: (res) => {
      if (res.result) {
        newRepoUrl.value = res.result
        addRepository()
      }
    },
    fail: (err) => {
      console.error(err)
      toast.show('扫描失败')
    },
  })
}

const openRepository = (item) => {
  // 这里可以实现打开知识库的逻辑
  const { owner, repo, name } = item
  const query = `owner=${owner}&repo=${repo}&name=${name}`
  uni.navigateTo({
    url: `/pages/index/index?${query}`,
  })
}

const loading = ref(false)
// 更新数据
const refreshRepInfo = async (book) => {
  if (loading.value) return
  loading.value = true
  const { owner, repo } = book
  const res = await giteeService.getFileContent(
    owner,
    repo,
    'config.json',
    true
  )
  const { name, desc } = res.content
  if (!name || (book.name == name && book.desc == desc)) {
    toast.show('已是最新版本')
    loading.value = false
    return
  }
  book.name = name
  book.desc = desc
  await updateUserInfo({
    repositories: repositories.value,
  })
  toast.show('更新成功')
  loading.value = false
}

const removeRepository = (repo) => {
  const list = repositories.value.filter((r) => !isSameRepo(r, repo))

  updateUserInfo({
    repositories: list,
  })
}
</script>

<style scoped>
.more-tools {
  position: relative;
  margin: 0 40rpx;
  padding-top: 40rpx;
  padding-bottom: 20rpx;
  display: flex;
}
.more-tools::after {
  content: '';
  position: absolute;
  border-bottom: 1px solid #ddd;
  left: 0;
  right: 0;
  bottom: 0;
  transform: scaleY(0.5);
}

.repositories-content {
  padding: 40rpx;
}
.sub-cell-ope {
  display: flex;
}
.popup-content {
  padding: 40rpx;
  padding-top: 280rpx;
}
.popup-input {
  margin-bottom: 20rpx;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.popup-opes {
  display: flex;
  align-items: center;
}
:deep(.popup-btn-add.popup-btn-add) {
  flex: 1;
  margin-right: 20rpx;
}
.sub-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.sub-title {
  font-size: 28rpx;
}
.btn-add {
  padding: 4px;
  font-size: 28rpx;
  margin-right: 4px;
}
.repositories-list {
  margin-top: 20rpx;
  /* padding-left: 20rpx; */
}
.no-repositories {
  text-align: center;
  color: #999;
  margin-top: 40rpx;
}

.the-btn {
  margin-right: 16rpx;
  line-height: 1;

  font-size: 28rpx;
  padding: 16rpx;
  border-radius: 40rpx;
  background-color: gray;
  color: white;
  border: 1rpx solid;
}

.c-blue {
  background-color: white;
  color: #333;
}
</style>
